//
//  MyViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/8.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//


#import "MemberInformationViewController.h"
#import "TagView.h"
#import "MemberAddressViewController.h"
#import "TheEditingViewController.h"
#import "MemberInformationCell.h"
#import "ForgotPasswordViewController.h"
@interface MemberInformationViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate, UITextViewDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,TheEditingViewControllerDelegate,ForgotPasswordViewControllerDelegate,UITextFieldDelegate>

{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSArray *array;
    NSArray *array1;
    NSDictionary*Dict;
    UITableView*table;
    UIView*myToolBar;
}
@property(nonatomic,retain)UIDatePicker* da1;
@end

@implementation MemberInformationViewController
@synthesize alt = alt;
@synthesize delegate;

-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNavigation];
   
}
-(void)viewDidLoad{
    [super viewDidLoad];
    [self update];
    array = @[@"编号",@"姓名",@"微信昵称",@"会员来源",@"电话",@"性别",@"生日",@"收货地址"];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:keyboardFot];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];

    _da1 = [[UIDatePicker alloc] init];
    [_da1 addTarget:self action:@selector(dateChanged1:) forControlEvents:UIControlEventValueChanged];
    _da1.datePickerMode = UIDatePickerModeDate;
    _da1.backgroundColor=[UIColor whiteColor];
   

}
-(void)OnTapDone{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    table .frame =CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
    [_birthDateTextFied resignFirstResponder];
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:self.memberId forKey:@"id"];
    [params setValue:_birthDateTextFied.text forKey:@"birthDate"];
    NSLog(@"------%@",params);
    [HttpRequest requestData:@"Business/Member/Edit" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                [delegate update:@""];
                [self update];
            }else{
                
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];

    
}
- (void)update
{
   
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.memberId forKey:@"memberId"];
    
    [HttpRequest requestData:@"Business/Member/Detail" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"------%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                Dict=[[NSDictionary alloc]init];
                Dict=severDataDict.dataDict ;
                if ([Dict valueForKey:@"birthDate"]==NULL||[[Global getJudgeTheErrorStr:[Dict valueForKey:@"birthDate"]]isEqualToString:@""]){
                
                }else{
                    if ([[NSString stringWithFormat:@"%@",[Dict objectForKey:@"birthDate"]]length]==10) {
                        _da1.date =[self dateFromString:[NSString stringWithFormat:@"%@",[Dict objectForKey:@"birthDate"]]];
                    }
                }
                table.delegate = self;
                table.dataSource = self;
                [table reloadData];
                
                }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:requestResultStr delegate:self cancelButtonTitle:@"确定返回" otherButtonTitles: nil];
                [alert show];
                
            }}
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
}
- (void)secondViewController:(ForgotPasswordViewController *)secondViewController updateMemberPhoneText:(NSString *)memberPhoneText{
    
    [delegate update:@""];
    [self update];

}
- (void)secondViewController:(TheEditingViewController *)secondViewController updateUserNameText:(NSString *)userNameStr updateSexStr:(NSString *)sexStr updateMemoStr:(NSString *)memoStr
{
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* Token = [user objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
    
            [params setValue:Token forKey:@"tokenId"];
            [params setValue:self.memberId forKey:@"id"];
            [params setValue:userNameStr forKey:@"userName"];
            [params setValue:sexStr forKey:@"sex"];
            [HttpRequest requestData:@"Business/Member/Edit" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                       
                        [delegate update:@""];
                        [self update];
                    }else{
                      
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }
    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
                
            }];
}
#pragma mark--TableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    static NSString *CellIdentifier = @"Cell";
    
    MemberInformationCell* cell = (MemberInformationCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[MemberInformationCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    
   
    UIButton*jiantou1 = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-40,7.5, 33, 33)];
    cell.accessoryView = jiantou1;

    cell.textLabel.font=[UIFont systemFontOfSize:titleNamefot];
    cell.textLabel.textColor=[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"编号"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-200, 0, 186, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"cardNo"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1]; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
    
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"姓名"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"userName"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,10, 30, 30);
         jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"微信昵称"]) {
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"nickName"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
        label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];

    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"会员来源"]) {
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"staffName"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
        label.font=[UIFont systemFontOfSize:  14];
        [cell.contentView addSubview:label];
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"电话"]) {
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"phone"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
         label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,10, 30, 30);
        jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"性别"]) {
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"sex"]];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
        label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,10, 30, 30);
         jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"生日"]) {

    
        
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,10, 30, 30);
        jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
        _birthDateTextFied=[[UITextField alloc]initWithFrame:CGRectMake(ScreenWidth-255, 0, 210, 50)];
        _birthDateTextFied.borderStyle = UITextBorderStyleNone;
        _birthDateTextFied.font = [UIFont systemFontOfSize: 15];
        _birthDateTextFied.textColor=zhonghuiColor;
        _birthDateTextFied.placeholder= @"请选择生日日期"; //默认显示的字
        _birthDateTextFied.textAlignment=NSTextAlignmentRight;
        _birthDateTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
        _birthDateTextFied.tag=11;
        _birthDateTextFied.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"birthDate"]];
        _birthDateTextFied.delegate = self;
        _birthDateTextFied.inputView = _da1;
        _birthDateTextFied.inputAccessoryView= myToolBar;
        [cell.contentView addSubview:_birthDateTextFied];

    }

    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"收货地址"]) {
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 50)];
        label.text=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"addrQty"]];

        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,10, 30, 30);
         jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    if (array.count ==indexPath.row+1) {
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(10, 50-0.40, ScreenWidth-20, 0.40)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
        
    }
    if (array.count !=indexPath.row+1) {
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(10, 50-0.40, ScreenWidth-20, 0.3)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell =(UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.textLabel.text isEqualToString:@"姓名"]) {
        
        TheEditingViewController * detailViewController=[[TheEditingViewController alloc]init];
        detailViewController.type=@"userName";
        detailViewController.userNameStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"userName"]];
        detailViewController.sexStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"sex"]];
        detailViewController.memoStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"memo"]];
        detailViewController.titleName=@"姓名";
        detailViewController.delegate = self;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
    if ([cell.textLabel.text isEqualToString:@"生日"]) {
       
        
        
        [_birthDateTextFied becomeFirstResponder];
        
        
    }
    if ([cell.textLabel.text isEqualToString:@"性别"]) {
        TheEditingViewController * detailViewController=[[TheEditingViewController alloc]init];
        detailViewController.type=@"sex";
        detailViewController.userNameStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"userName"]];
        detailViewController.sexStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"sex"]];
        detailViewController.memoStr=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"memo"]];
        detailViewController.titleName=@"性别";
        detailViewController.delegate = self;
        [self.navigationController pushViewController:detailViewController animated:YES];
        
        
    }
    if ([cell.textLabel.text isEqualToString:@"收货地址"]) {
        MemberAddressViewController *detailViewController = [[MemberAddressViewController alloc] init];
        detailViewController.memberId=self.memberId;
        detailViewController.userName=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"userName"]];
        detailViewController.phone=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"phone"]];
        detailViewController.sex=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"sex"]];
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
    
    if ([cell.textLabel.text isEqualToString:@"电话"]) {//找回密码和绑定手机同样界面
        ForgotPasswordViewController *detailViewController = [[ForgotPasswordViewController alloc] init];
        detailViewController.userName=[NSString stringWithFormat:@"%@",[Dict objectForKey:@"userName"]];
         detailViewController.memberId=self.memberId;
        detailViewController.titleName=@"绑定手机";
        detailViewController.delegate = self;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
    
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
   
    if (textField.tag == 11)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        table .frame =CGRectMake(0, -100, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
    }
    
}

-(void)dateChanged1:(UIButton*)sender{
   
    UIDatePicker* picker = (UIDatePicker*)sender;
   
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    if ([_birthDateTextFied isFirstResponder])
    {
        _birthDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
    }else{
        
        _birthDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
     if(textField.tag==11){
        
        if (textField.text.length<1) {
            NSDateFormatter* df = [[NSDateFormatter alloc] init];
            [df setDateFormat:@"yyyy-MM-dd"];
            _birthDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
        }
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (array.count==0) {
        return 118/2;
    }
    return  50;
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)setNavigation{
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    self.title = @"会员基本详情";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
  
}
- (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    
    
    return destDate;
    
}

@end
